iT邦幫忙

2023 iThome 鐵人賽

DAY 16
0
Software Development

LeetCode-30 Days of JavaScript系列 第 16

LeetCode JS30-Day16 | 2637. Promise Time Limit 有時間限制的Promise

  • 分享至 

  • xImage
  •  

Day16 - 2637. Promise Time Limit 有時間限制的Promise Medium

Description❓

Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function.
fn takes arguments provided to the time limited function.

The time limited function should follow these rules:

If the fn completes within the time limit of t milliseconds, the time limited function should resolve with the result.
If the execution of the fn exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded".

給定非同步函數fn和以毫秒為單位的時間t作為參數,返回一個對輸入函數fn添加時間限制版本的新函數。
原始函數fn會使用限時函數(time limited function)所傳遞的參數進行調用。

限時函數應遵循以下規則:
如果 fnt 毫秒的時間限制內完成,則限時函數應解析結果。
如果 fn 的執行時間超過t毫秒的限時,則時間限制函數應拒絕並顯示字串"Time Limit Exceeded"

Points

Solution✍️

[ ▶️挑戰這一題 ][ 本日代碼 ]

function timeLimit(fn, t) {
    return (...args) => {
        const originalPromise = fn(...args);
        const timeoutPromise = new Promise((resolve, reject) => {
            setTimeout(() => {
                reject("Time Limit Exceeded");
            }, t);
        });

        return Promise.race([originalPromise, timeoutPromise]);
    };
}

Testcase

const fn1 = async (n) => {
    await new Promise(res => setTimeout(res, 100));
    return n * n;
}
const inputs1 = [5];
const t1 = 50;

const test1 = timeLimit(fn1, t1);

test1(...inputs1)
    .then(result => { console.log(result); })
    .catch(error => { console.error(error); });
//輸出:Time Limit Exceeded
const fn2 = async (n) => {
    await new Promise(res => setTimeout(res, 100));
    return n * n;
}
const inputs2 = [5];
const t2 = 150;

const test2 = timeLimit(fn2, t2);

test2(...inputs2)
    .then(result => { console.log(result); })
    .catch(error => { console.error(error); });
//輸出:25
const fn3 = async (a, b) => {
    await new Promise(res => setTimeout(res, 120));
    return a + b;
}
const inputs3 = [5, 10];
const t3 = 150;

const test3 = timeLimit(fn3, t3);

test3(...inputs3)
    .then(result => { console.log(result); })
    .catch(error => { console.error(error); });
//輸出:15
const fn4 = async () => {
    throw "Error";
}
const inputs4 = [];
const t4 = 1000;

const test4 = timeLimit(fn4, t4);

test4(...inputs4)
    .then(result => { console.log(result); })
    .catch(error => { console.error(error); });
//輸出:Error

上一篇
LeetCode JS30-Day15 | 2725. Interval Cancellation 間隔取消
下一篇
LeetCode JS30-Day17 | 2622. Cache With Time Limit 有時間限制的緩存Cache
系列文
LeetCode-30 Days of JavaScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言